package com.example.cxf.config;

import com.example.cxf.interceptor.WebserviceAuthInterceptor;
import com.example.cxf.webservice.VehicleWebservice;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class WebserviceConfig {

    @Autowired
    private SpringBus bus;

    @Autowired
    private VehicleWebservice vehicleWebservice;

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, vehicleWebservice);

        //拦截器，用于日志、授权等等；如果不需要，直接注释好了。
        endpoint.getInInterceptors().addAll(Lists.newArrayList(
                new LoggingInInterceptor(), // 请求日志拦截器
                new WebserviceAuthInterceptor() // 登录认证的拦截器
        ));
        endpoint.getOutInterceptors().addAll(Lists.newArrayList(
                new LoggingOutInterceptor() // 返回日志拦截器
        ));

//        //将serviceName作为线程池前缀
//        WebService annotation = vehicleWebservice.getClass().getAnnotation(WebService.class);
//        String prefix = annotation.serviceName();
//        ThreadPoolExecutor executor = new ThreadPoolExecutor(
//                10,
//                50,
//                2L,
//                TimeUnit.SECONDS,
//                new LinkedBlockingQueue<>(),
//                new BasicThreadFactory.Builder().namingPattern(prefix + "-thread-pool-%d").daemon(true).build(),
//                new ThreadPoolExecutor.CallerRunsPolicy());
//
//        //设置线程池
//        endpoint.setExecutor(executor);

        endpoint.publish("/vehicleService");
        return endpoint;
    }
}
